package com.apptest.android.ui.ArticleList;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.apptest.android.R;
import com.apptest.android.core.Constants;
import com.apptest.android.databinding.FragmentCommonRecylerviewBinding;
import com.apptest.android.ui.common.CommonActivity;

public class ArticleListFragment extends Fragment {
    private ArticleListViewModel articleListViewModel;
    private FragmentCommonRecylerviewBinding binding;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        binding = FragmentCommonRecylerviewBinding.inflate(inflater, container, false);
        articleListViewModel = new ViewModelProvider(this).get(ArticleListViewModel.class);
        initSource();
        initView();

        return binding.getRoot();
    }

    private void initSource(){
        Bundle bundle = getArguments();
        assert bundle != null;
        articleListViewModel.setArticleListSource(
                bundle.getInt(Constants.ARTICLE_SOURCE),
                bundle.getInt(Constants.SOURCE_ID)
        );
        articleListViewModel.updateArticleList(true);
    }

    private void initView(){
        ArticleListAdapter articleAdapter = new ArticleListAdapter(
                R.layout.item_article_list, articleListViewModel.getArticleItemList().getValue()
        );
        articleAdapter.setOnItemClickListener((adapter, view, position) -> {
            int mAdapterSize = articleAdapter.getData().size();
            if (mAdapterSize <= 0 || mAdapterSize < position) {
                return;
            }
            CommonActivity.startCommonActivity(getContext(),
                    articleAdapter.getData().get(position).getTitle(),
                    articleAdapter.getData().get(position).getLink());
        });
        binding.commonRecyclerView.setAdapter(articleAdapter);
        binding.commonRecyclerView.setLayoutManager(new LinearLayoutManager(
                getActivity(), LinearLayoutManager.VERTICAL, false
        ));
        articleListViewModel.getArticleItemList().observe(getViewLifecycleOwner(),
                articleAdapter::replaceData);

        binding.commonRefreshLayout.setOnRefreshListener(refreshLayout -> {
            articleListViewModel.updateArticleList(true);
            refreshLayout.finishRefresh();
        });
    }

    //为了传递数据来源和更新方式
    public static ArticleListFragment newInstance(Bundle bundle){
        ArticleListFragment fragment = new ArticleListFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }
}
